/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller.view;

import entity.Contact;
import entity.ContactCompany;
import entity.JobAction;
import entity.JobItems;
import entity.JobPeriod;
import entity.JobStatusStatement;
import entity.Jobs;
import entity.Message;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import session.ContactCompanyFacade;
import session.ContactFacade;
import session.JobActionFacade;
import session.JobItemsFacade;
import session.JobPeriodFacade;
import session.JobStatusFacade;
import session.JobStatusStatementFacade;
import session.JobsFacade;
import session.MessageFacade;

/**
 *
 * @author owtee
 */
public class ApplicationAdd extends HttpServlet {

    @EJB
    private JobStatusFacade jobStatusFacade;
    @EJB
    private JobStatusStatementFacade jobStatusStatementFacade;
    @EJB
    private JobItemsFacade jobItemsFacade;
    @EJB
    private JobActionFacade jobActionFacade;
    @EJB
    private ContactFacade contactFacade;
    @EJB
    private ContactCompanyFacade contactCompanyFacade;
    @EJB
    private JobPeriodFacade jobPeriodFacade;
    @EJB
    private JobsFacade jobsFacade;
    @EJB
    private MessageFacade messageFacade;

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            try {
                String hdJobId = request.getParameter("hdJobId");

                String txtExpectDate = request.getParameter("txtExpectDate");
                String ddlPeriod = request.getParameter("ddlPeriod");
                String txtRemark = request.getParameter("txtRemark");
                String ddlConCom = request.getParameter("ddlConCom");
                String ddlCon = request.getParameter("ddlCon");

                // Find job
                Jobs job = jobsFacade.find(hdJobId);

                // Validate data
                List<Message> mesLst = new ArrayList<Message>();

                if (txtExpectDate.equals("")) {
                    Message message = messageFacade.find("026");
                    mesLst.add(message);
                }

                if (ddlPeriod.equals("")) {
                    Message message = messageFacade.find("027");
                    mesLst.add(message);
                }

                if (ddlConCom.equals("")) {
                    Message message = messageFacade.find("006");
                    mesLst.add(message);
                }

                if (ddlCon.equals("")) {
                    Message message = messageFacade.find("009");
                    mesLst.add(message);
                }

                if (job.getJobDetailsCollection().isEmpty()) {
                    Message message = messageFacade.find("028");
                    mesLst.add(message);
                }

                if (mesLst.size() > 0) {

                    job.setRemark(txtRemark);

                    if (!txtExpectDate.equals("")) {
                        SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy", Locale.US);
                        Date dExpectDate = dateFormat.parse(txtExpectDate);
                        job.setExpectDate(dExpectDate);
                    }

                    if (!ddlPeriod.equals("")) {
                        job.setPeriodId(jobPeriodFacade.find(Integer.parseInt(ddlPeriod)));
                    }

                    if (!ddlCon.equals("")) {

                        List<Integer> iConCom = new ArrayList<Integer>();
                        iConCom.add(Integer.parseInt(ddlConCom));

                        List<Contact> conLst = contactFacade.findByConComId(iConCom);
                        request.setAttribute("conLst", conLst);

                        job.setConId(contactFacade.find(Integer.parseInt(ddlCon)));
                    }

                    List<JobPeriod> jobPeriodLst = jobPeriodFacade.findByActiveFlag(true);
                    List<ContactCompany> conComLst = contactCompanyFacade.findByActiveFlag(true);

                    // Set job detail
                    List<JobAction> jobActionLst = jobActionFacade.findByActiveFlag(true);
                    List<JobItems> jobItemLst = jobItemsFacade.findByActiveFlag(true);

                    request.setAttribute("mesLst", mesLst);
                    request.setAttribute("job", job);
                    request.setAttribute("jobPeriodLst", jobPeriodLst);
                    request.setAttribute("conComLst", conComLst);
                    // Set attr to job detail
                    request.setAttribute("jobActionLst", jobActionLst);
                    request.setAttribute("jobItemLst", jobItemLst);

                    RequestDispatcher rd = request.getRequestDispatcher("application_add.jsp");
                    rd.forward(request, response);

                    return;
                }
                // End Validate data

                // Set data before update
                SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy", Locale.US);
                Date dExpectDate = dateFormat.parse(txtExpectDate);

                job.setExpectDate(dExpectDate);
                job.setPeriodId(jobPeriodFacade.find(Integer.parseInt(ddlPeriod)));
                // Check period urgent or not
                if (ddlPeriod.equals("4")) {
                    job.setUrgentDate(new Date());
                }
                job.setRemark(txtRemark);
                job.setConId(contactFacade.find(Integer.parseInt(ddlCon)));
                job.setStatusId(jobStatusFacade.find("01"));
                job.setModifyDate(new Date());
                jobsFacade.edit(job);

                // Create job status statement
                JobStatusStatement jobStatusStatement = new JobStatusStatement();
                jobStatusStatement.setJobId(job);
                jobStatusStatement.setStatusId(jobStatusFacade.find("01"));
                jobStatusStatement.setCreateUser(job.getRequestUser().getUserId());
                jobStatusStatement.setCreateDate(new Date());
                jobStatusStatement.setModifyUser(job.getRequestUser().getUserId());
                jobStatusStatement.setModifyDate(new Date());
                jobStatusStatementFacade.create(jobStatusStatement);
                
                Message message = messageFacade.find("101");
                request.setAttribute("message", message);

            } catch (Exception ex) {
                // Found error
                Message message = messageFacade.find("002");
                String m = message.getMesDetail() + " : " + ex.getMessage();
                message.setMesDetail(m);
                request.setAttribute("message", message);
            }

            RequestDispatcher rd = request.getRequestDispatcher("ApplicationReqGetAll");
            rd.forward(request, response);

        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
